﻿using System.ServiceModel;
using System.ServiceProcess;

namespace WOLGateway.WindowsService
{
    /// <summary>
    /// WolService
    /// </summary>
    public partial class WindowsService : ServiceBase
    {
        /// <summary>
        /// ServiceHost
        /// </summary>
        private static ServiceHost serviceHost = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="WindowsService"/> class.
        /// </summary>
        public WindowsService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Start the Windows service.
        /// </summary>
        /// <param name="args">Data passed by the start command.</param>
        protected override void OnStart(string[] args)
        {
            Close();
            Open();
        }

        /// <summary>
        /// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
        /// </summary>
        protected override void OnStop()
        {
            Close();
        }

        /// <summary>
        /// Opens this instance.
        /// </summary>
        public void Open()
        {
            // Create a ServiceHost for the Wake On LAN Service type and 
            // provide the base address.
            serviceHost = new ServiceHost(typeof(WOLGateway.WCFServiceLibrary.WakeOnLan));

            // Open the ServiceHostBase to create listeners and start 
            // listening for messages.
            serviceHost.Open();
        }

        /// <summary>
        /// Closes this instance.
        /// </summary>
        public void Close()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }
}